/**
 * Copyright (c) 2023 murenchao
 * taomu is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *       http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package cool.taomu.lang

import java.io.IOException
import org.eclipse.xtend.lib.annotations.Accessors
import org.apache.groovy.util.concurrent.concurrentlinkedhashmap.ConcurrentLinkedHashMap
import org.apache.groovy.util.concurrent.concurrentlinkedhashmap.Weighers

@Accessors
class MultiClassLoader extends ClassLoader {
	protected ConcurrentLinkedHashMap<String, AbsWrapperClassLoader> cache = new ConcurrentLinkedHashMap.Builder<String, AbsWrapperClassLoader>().maximumWeightedCapacity(512).weigher(
		Weighers.singleton()).listener(
		[ key, value |
			try {
				value.close();
			} catch (IOException e) {
				throw new RuntimeException(e);
			}
		]
	).build();

	new() {
	}

	static class JarMultiClassLoader extends MultiClassLoader {
		val static instance = new JarMultiClassLoader();

		private new() {
		}

		def static getInstance() {
			return instance;
		}

	}

	static class GroovyMultiClassLoader extends MultiClassLoader {
		val static instance = new GroovyMultiClassLoader();

		private new() {
		}

		def static getInstance() {
			return instance;
		}
	}

	override findClass(String name) {
		if (cache.size > 0) {
			var clc = cache.values.findFirst [
				return it.loadClass(name) !== null;
			]
			return clc.loadClass(name);
		}
		return null;
	}
}
